package com.atguigu.tingshu.user.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.entity.GuiguCorrelationData;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.model.user.UserPaidAlbum;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.user.mapper.UserPaidAlbumMapper;
import com.atguigu.tingshu.user.mapper.UserPaidTrackMapper;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private WxMaService wxMaService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RabbitService rabbitService;
    @Autowired
    private UserPaidAlbumMapper userPaidAlbumMapper;
    @Autowired
    private UserPaidTrackMapper userPaidTrackMapper;

    @SneakyThrows
    @Override
    public Map<String, String> wxLoginBycode(String code) {
        //微信校验认证接口

        WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
        //判断是否认证成功
        if (BeanUtil.isNotEmpty(sessionInfo)) {
            //是 获取seesionkey+openid
            String openid = sessionInfo.getOpenid();
            if (openid != null) {
                //openid 是否有对应的user_info
                UserInfo userInfo = userInfoMapper.selectOne(new QueryWrapper<UserInfo>().eq("wx_open_id", openid));
                if (userInfo == null) {
                    //没有注册user_info 初始化账户
                    userInfo = new UserInfo();
                    userInfo.setWxOpenId(openid);
                    userInfo.setNickname(IdUtil.getSnowflakeNextIdStr());
                    userInfo.setAvatarUrl("https://q8.itc.cn/q_70/images03/20241030/7e4e379bf5b84b6c9fb4a9fec3102d5d.jpeg");
                    userInfoMapper.insert(userInfo);
                    //注册账户
                    rabbitService.sendMessage(MqConst.EXCHANGE_USER,MqConst.ROUTING_USER_REGISTER,userInfo.getId());


                }
                //生成token 存入redis
                String token = IdUtil.getSnowflakeNextIdStr();
                String tokenKey = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
                UserInfoVo userInfoVo = BeanUtil.copyProperties(userInfo, UserInfoVo.class);
                redisTemplate.opsForValue().set(tokenKey, userInfoVo, RedisConstant.USER_LOGIN_KEY_TIMEOUT, TimeUnit.SECONDS);

                //返回token
                HashMap<String, String> tokenMap = new HashMap<>();
                tokenMap.put("token", token);
                return tokenMap;
            }
        }
        return null;
    }

    @Override
    public Map<Long, Integer> userPaidTrack(List<Long> waitCheckTrackIdList, Long userId, Long albumId) {
        //构建查询条件
        LambdaQueryWrapper<UserPaidAlbum> userPaidAlbumLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userPaidAlbumLambdaQueryWrapper.eq(UserPaidAlbum::getUserId,userId);
        userPaidAlbumLambdaQueryWrapper.eq(UserPaidAlbum::getAlbumId,albumId);

        //根据用户ID和专辑ID查询专辑购买记录表
        Long count = userPaidAlbumMapper.selectCount(userPaidAlbumLambdaQueryWrapper);
        //判断
        if(count>0){
            //转换成map
            Map<Long, Integer> resultMap = waitCheckTrackIdList.stream().collect(Collectors.toMap(trackId -> trackId, trackId -> 1));
            return resultMap;

        }
        //构建声音查询条件对象
        QueryWrapper<UserPaidTrack> userPaidTrackQueryWrapper = new QueryWrapper<>();
        userPaidTrackQueryWrapper.eq("user_id",userId);
        userPaidTrackQueryWrapper.eq("album_id",albumId);

        //根据用户ID和专辑ID查询声音购买记录  22 23
        List<UserPaidTrack> buyUserPaidTrackList = userPaidTrackMapper.selectList(userPaidTrackQueryWrapper);
        //获取购买的id列表
        List<Long> buyUserPaidTrackIdList = buyUserPaidTrackList.stream().map(userPaidTrack -> userPaidTrack.getTrackId()).collect(Collectors.toList());

        //判断
        if(CollectionUtils.isEmpty(buyUserPaidTrackList)){

            //转换成map
            Map<Long, Integer> resultMap = waitCheckTrackIdList.stream().collect(Collectors.toMap(trackId -> trackId, trackId -> 0));
            return resultMap;

        }


        Map<Long,Integer> resultMap=new HashMap<>();
        //查询声音付费记录有结果
        waitCheckTrackIdList.forEach(trackId->{

            //判断 查询购买的结果中是否包含遍历的声音ID
            if(buyUserPaidTrackIdList.contains(trackId)){
                resultMap.put(trackId,1);

            }else{
                resultMap.put(trackId,0);

            }
        });
        return resultMap;
    }

}
